Convolutional Neural Networks

Project: Write an Algorithm for a Dog Identification App


In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the Jupyter Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a 'Question X' header. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. If you decide to pursue the "Stand Out Suggestions", you should include the code in this Jupyter notebook.


Why We're Here

In this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app. At the end of this project, your code will accept any user-supplied image as input. If a dog is detected in the image, it will provide an estimate of the dog's breed. If a human is detected, it will provide an estimate of the dog breed that is most resembling. The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!).

Sample Dog Output

In this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed. There are many points of possible failure, and no perfect algorithm exists. Your imperfect solution will nonetheless create a fun user experience!

The Road Ahead

We break the notebook into separate steps. Feel free to use the links below to navigate the notebook.

  • Step 0: Import Datasets
  • Step 1: Detect Humans
  • Step 2: Detect Dogs
  • Step 3: Create a CNN to Classify Dog Breeds (from Scratch)
  • Step 4: Create a CNN to Classify Dog Breeds (using Transfer Learning)
  • Step 5: Write your Algorithm
  • Step 6: Test Your Algorithm

Step 0: Import Datasets

Make sure that you've downloaded the required human and dog datasets:

  • Download the dog dataset. Unzip the folder and place it in this project's home directory, at the location /dogImages.

  • Download the human dataset. Unzip the folder and place it in the home diretcory, at location /lfw.

Note: If you are using a Windows machine, you are encouraged to use 7zip to extract the folder.

In the code cell below, we save the file paths for both the human (LFW) dataset and dog dataset in the numpy arrays human_files and dog_files.

In [1]:
import numpy as np
from glob import glob

# load filenames for human and dog images
human_files = np.array(glob("lfw/*/*/*"))
dog_files = np.array(glob("dogImages/*/*/*"))

# print number of images in each dataset
print('There are %d total human images.' % len(human_files))
print('There are %d total dog images.' % len(dog_files))
There are 18982 total human images.
There are 8351 total dog images.

Step 1: Detect Humans

In this section, we use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images.

OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the haarcascades directory. In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.

In [2]:
import cv2                
import matplotlib.pyplot as plt                        
%matplotlib inline                               

# extract pre-trained face detector
face_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')

# load color (BGR) image
img = cv2.imread(human_files[0])
# convert BGR image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# find faces in image
faces = face_cascade.detectMultiScale(gray)

# print number of faces detected in the image
print('Number of faces detected:', len(faces))

# get bounding box for each detected face
for (x,y,w,h) in faces:
    # add bounding box to color image
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
    
# convert BGR image to RGB for plotting
cv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# display the image, along with bounding box
plt.imshow(cv_rgb)
plt.show()
Number of faces detected: 1

Before using any of the face detectors, it is standard procedure to convert the images to grayscale. The detectMultiScale function executes the classifier stored in face_cascade and takes the grayscale image as a parameter.

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.

Write a Human Face Detector

We can use this procedure to write a function that returns True if a human face is detected in an image and False otherwise. This function, aptly named face_detector, takes a string-valued file path to an image as input and appears in the code block below.

In [3]:
# returns "True" if face is detected in image stored at img_path
def face_detector(img_path):
    img = cv2.imread(img_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)
    return len(faces) > 0

(IMPLEMENTATION) Assess the Human Face Detector

Question 1: Use the code cell below to test the performance of the face_detector function.

  • What percentage of the first 100 images in human_files have a detected human face?
  • What percentage of the first 100 images in dog_files have a detected human face?

Ideally, we would like 100% of human images with a detected face and 0% of dog images with a detected face. You will see that our algorithm falls short of this goal, but still gives acceptable performance. We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays human_files_short and dog_files_short.

Answer: (You can print out your results and/or write your percentages in this cell)

In [4]:
from tqdm import tqdm

human_files_short = human_files[:100]
dog_files_short = dog_files[:100]

#-#-# Do NOT modify the code above this line. #-#-#

## TODO: Test the performance of the face_detector algorithm 
## on the images in human_files_short and dog_files_short.
def human_face_detection_performance_analysis(list_of_img_filepaths, image_class_type):
    humans = 0
    for img_filepath in list_of_img_filepaths:
        if face_detector(img_filepath): 
            humans = humans + 1
    human_pct = humans*100/len(list_of_img_filepaths)
    print('{0} percentage of the first {1} images in {2}_files have a detected human face.'.format(human_pct, len(list_of_img_filepaths), image_class_type))

print('Question 1: Assess the Human Face Detector')
human_face_detection_performance_analysis(human_files_short, 'human')
human_face_detection_performance_analysis(dog_files_short, 'dog')
Question 1: Assess the Human Face Detector
98.0 percentage of the first 100 images in human_files have a detected human face.
17.0 percentage of the first 100 images in dog_files have a detected human face.

We suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :). Please use the code cell below to design and test your own face detection algorithm. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.

In [5]:
### (Optional) 
### TODO: Test performance of anotherface detection algorithm.
### Feel free to use as many code cells as needed.

Step 2: Detect Dogs

In this section, we use a pre-trained model to detect dogs in images.

Obtain Pre-trained VGG-16 Model

The code cell below downloads the VGG-16 model, along with weights that have been trained on ImageNet, a very large, very popular dataset used for image classification and other vision tasks. ImageNet contains over 10 million URLs, each linking to an image containing an object from one of 1000 categories.

In [6]:
import torch
import torchvision.models as models

# define VGG16 model
VGG16 = models.vgg16(pretrained = True)

# check if CUDA is available
use_cuda = torch.cuda.is_available()

# move model to GPU if CUDA is available
if use_cuda: VGG16 = VGG16.cuda()

Given an image, this pre-trained VGG-16 model returns a prediction (derived from the 1000 possible categories in ImageNet) for the object that is contained in the image.

(IMPLEMENTATION) Making Predictions with a Pre-trained Model

In the next code cell, you will write a function that accepts a path to an image (such as 'dogImages/train/001.Affenpinscher/Affenpinscher_00001.jpg') as input and returns the index corresponding to the ImageNet class that is predicted by the pre-trained VGG-16 model. The output should always be an integer between 0 and 999, inclusive.

Before writing the function, make sure that you take the time to learn how to appropriately pre-process tensors for pre-trained models in the PyTorch documentation.

In [7]:
# Normalizing reference: https://pytorch.org/docs/stable/torchvision/models.html
# Reference: https://stackoverflow.com/questions/50063514/load-a-single-image-in-a-pretrained-pytorch-net
# Resize rerefence: https://machinelearningmastery.com/use-pre-trained-vgg-model-classify-objects-photographs/
# Fixed image trancate issue reference: 

from PIL import Image, ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
import torchvision.transforms as transforms

def VGG16_predict(img_path, debug = False):
    '''
    Use pre-trained VGG-16 model to obtain index corresponding to 
    predicted ImageNet class for image at specified path
    
    Args:
        img_path: path to an image
        
    Returns:
        Index corresponding to VGG-16 model's prediction
    '''
    
    ## TODO: Complete the function.
    ## Load and pre-process an image from the given img_path
    ## Return the *index* of the predicted class for that image
    img = Image.open(img_path)
    
    if debug: print(type(img)) # Remove
        
    data_transform = transforms.Compose([transforms.Resize(size=(224, 224)),
                                         transforms.ToTensor(),
                                         transforms.Normalize(
                                             mean = [0.485, 0.456, 0.406], 
                                             std  = [0.229, 0.224, 0.225])])
    
    VGG16.eval()
    
    if debug: print(data_transform(img).size()) # Remove
        
    # Transform: Properly reshape, convert to tensor, and normalize according to VGG16 rules
    input_img_tensor = data_transform(img).reshape(1, 3, 224, 224)
                             
    # move tensors to GPU if CUDA is available
    use_cuda = torch.cuda.is_available()
    if use_cuda: input_img_tensor = input_img_tensor.cuda() 
    
    if debug: print(input_img_tensor.size()) # Remove                         
        
    # forward pass: compute predicted outputs by passing inputs to the model
    output = VGG16(input_img_tensor)
    
    # convert output probabilities to predicted class
    # predicted class index
    _, pred_class_idx = torch.max(output, 1)
    return pred_class_idx

output = VGG16_predict('./dogImages/train/001.Affenpinscher/Affenpinscher_00001.jpg')
print(output)
tensor([252], device='cuda:0')

(IMPLEMENTATION) Write a Dog Detector

While looking at the dictionary, you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from 'Chihuahua' to 'Mexican hairless'. Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained VGG-16 model, we need only check if the pre-trained model predicts an index between 151 and 268 (inclusive).

Use these ideas to complete the dog_detector function below, which returns True if a dog is detected in an image (and False if not).

In [8]:
### returns "True" if a dog is detected in the image stored at img_path
def dog_detector(img_path):
    ## TODO: Complete the function.
    
    output = VGG16_predict(img_path)
    if output >= 151 and output <= 268: return True
    return False

(IMPLEMENTATION) Assess the Dog Detector

Question 2: Use the code cell below to test the performance of your dog_detector function.

  • What percentage of the images in human_files_short have a detected dog?
  • What percentage of the images in dog_files_short have a detected dog?

Answer: (You can print out your results and/or write your percentages in this cell)

In [9]:
### TODO: Test the performance of the dog_detector function
### on the images in human_files_short and dog_files_short.

# prints the percentage of human face detected on the images, whose 
# image filepaths are stored in the variable list_of_img_filepaths
def dog_detection_performance_analysis(list_of_img_filepaths, image_class_type):
    dogs = 0
    for img_filepath in list_of_img_filepaths:
        if dog_detector(img_filepath): 
            dogs = dogs + 1
    dog_pct = dogs*100/len(list_of_img_filepaths)
    print('{0} percentage of the first {1} images in {2}_files_short have a detected dog.'.format(dog_pct, len(list_of_img_filepaths), image_class_type))

print('Question 2: Assess the Dog Detector')
dog_detection_performance_analysis(human_files_short, 'human')
dog_detection_performance_analysis(dog_files_short, 'dog')
Question 2: Assess the Dog Detector
0.0 percentage of the first 100 images in human_files_short have a detected dog.
100.0 percentage of the first 100 images in dog_files_short have a detected dog.

We suggest VGG-16 as a potential network to detect dog images in your algorithm, but you are free to explore other pre-trained networks (such as Inception-v3, ResNet-50, etc). Please use the code cell below to test other pre-trained PyTorch models. If you decide to pursue this optional task, report performance on human_files_short and dog_files_short.

In [10]:
### (Optional) 
### TODO: Report the performance of another pre-trained network.
### Feel free to use as many code cells as needed.

Step 3: Create a CNN to Classify Dog Breeds (from Scratch)

Now that we have functions for detecting humans and dogs in images, we need a way to predict breed from images. In this step, you will create a CNN that classifies dog breeds. You must create your CNN from scratch (so, you can't use transfer learning yet!), and you must attain a test accuracy of at least 10%. In Step 4 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.

We mention that the task of assigning breed to dogs from images is considered exceptionally challenging. To see why, consider that even a human would have trouble distinguishing between a Brittany and a Welsh Springer Spaniel.

Brittany Welsh Springer Spaniel

It is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).

Curly-Coated Retriever American Water Spaniel

Likewise, recall that labradors come in yellow, chocolate, and black. Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.

Yellow Labrador Chocolate Labrador Black Labrador

We also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.

Remember that the practice is far ahead of the theory in deep learning. Experiment with many different architectures, and trust your intuition. And, of course, have fun!

(IMPLEMENTATION) Specify Data Loaders for the Dog Dataset

Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dogImages/train, dogImages/valid, and dogImages/test, respectively). You may find this documentation on custom datasets to be a useful resource. If you are interested in augmenting your training and/or validation data, check out the wide variety of transforms!

In [11]:
# get class names as list from train directory structure
def get_classnames_from_dataset_directory_struct(dir_path):
    classes = np.array(glob(dir_path))
    classes.sort()
    return [classes[i][20:] for i in range(len(classes))]

# Finds the minimum image dimension in a image directory
def get_minimum_img_sz(train_directory):
    min_image_size = np.Inf 
    
    data_transform = transforms.Compose([transforms.ToTensor()])
    train_data = datasets.ImageFolder(train_directory, transform = data_transform)
    train_loader = torch.utils.data.DataLoader(train_data, batch_size = 1, shuffle = True)
    
    for image, label in train_loader:
        min_dim = min(image.size()[2], image.size()[3])
        if min_dim <= min_image_size: min_image_size = min_dim

    return min_image_size
In [12]:
import os
from torchvision import datasets

# get path of train, test and validation images
root_dir = './dogImages/'
train_dir = os.path.join(root_dir, 'train/')
valid_dir = os.path.join(root_dir, 'valid/')
test_dir = os.path.join(root_dir, 'test/')

# Get class data and print basic stat about the image dataset
classes = get_classnames_from_dataset_directory_struct(dir_path = train_dir + '*')
min_img_sz = get_minimum_img_sz(train_dir)
In [13]:
### TODO: Write data loaders for training, validation, and test sets
### Specify appropriate transforms, and batch_sizes

'''
    Resized image to a square with dimension of 128: For simplicity, we resized the image to a square, where the 
    resized image dimension equals to the power of 2. The exact size is the closest highest or equal power of 2 
    considering the minimum image size (independent of width and height) in the training dataset. For example the 
    minimum image dimension (independent of width and height) for the dogs training dataset is 112, so the resized 
    image size would be 128 which is 2^7. This is a very common strategy as highlighted in the lectures. This was 
    particularly done keeping considering the computational resouces required for images with higher dimensions. 

    Furthermore, selecting the resized image dimension as a power of 2 helps designing the layers of the CNN much 
    easier (depends on strides and padding), bacause the size of the intermediate CNN layers and output of the CNN 
    later becomes much straight forward.
'''

resz_img_sz = 2 ** (int(np.log2(min_img_sz - 1)) + 1)

### Load and transform data using ImageFolder
data_transform_train = transforms.Compose([transforms.Resize(size = (resz_img_sz, resz_img_sz)), 
                                           transforms.RandomRotation(10), transforms.ToTensor(), 
                                           transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

data_transform_other = transforms.Compose([transforms.Resize(size = (resz_img_sz, resz_img_sz)), transforms.ToTensor(), 
                                           transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])

train_data = datasets.ImageFolder(train_dir, transform = data_transform_train)
valid_data = datasets.ImageFolder(valid_dir, transform = data_transform_other)
test_data = datasets.ImageFolder(test_dir, transform = data_transform_other)

# Define dataloader parameters
batch_size = 32

# Prepare data loaders
train_loader = torch.utils.data.DataLoader(train_data, batch_size = batch_size, shuffle = True)
valid_loader = torch.utils.data.DataLoader(valid_data, batch_size = batch_size, shuffle = True)
test_loader = torch.utils.data.DataLoader(test_data, batch_size = batch_size, shuffle = True) 

loaders_scratch = {'train': train_loader, 'valid' : valid_loader, 'test' : test_loader}

### Print out some dataset stats
print('Num training images: ', len(train_data))
print('Num valid images: ', len(valid_data))
print('Num test images: ', len(test_data))
Num training images:  6680
Num valid images:  835
Num test images:  836

Question 3: Describe your chosen procedure for preprocessing the data.

  • How does your code resize the images (by cropping, stretching, etc)? What size did you pick for the input tensor, and why?
  • Did you decide to augment the dataset? If so, how (through translations, flips, rotations, etc)? If not, why not?

Answer:

Summary: After running 6 different structured experiments we have reached accuracy of 23% with the CNN model which has been designed from scratch. Based on the accuracy trends it can be hypothesized, given that we keep the CNN model constant (including the data processing steps) and increase the epoch from 50 to 100 it would lead to a better accuracy.

  • The image was simply resized to a square with dimension of 128 (a common strategy as highlighted in the lectures). For simplicity, we resized the image to a square, where the resized image dimension equals to the power of 2. The exact size is the closest highest or equal power of 2 considering the minimum image size (independent of width and height) in the training dataset. For example the minimum image dimension (independent of width and height) for the dogs training dataset is 112, so the resized image size would be 128 which is 2^7.
  • Furthermore, selecting the resized image dimension as a power of 2 helps designing the layers of the CNN much easier (depends on strides and padding), because manually computing the size of intermediate CNN layers and output of the CNN layer becomes much straight forward.
  • Input tensor size (1, 3, 128, 128).
  • Batch size of 32: Initially 32 was choosen primarily because of memory constraints in my personal laptop. The input tensor size considering batches (32, 3, 128, 128).
  • Simple Random Image Rotation within 10 degrees: Artificially augment the data by randomly rotation the image within 10 degrees.

The exact reason why we choose this particular procedure for the processing the data is outlined in the following as experiments, how learning from one experiment lead to the next. For detailed structured reasoning please study our experiments process.

  • Experiment 1:

    • The image was simply resized to a square with dimension of 128 (a common strategy as highlighted in the lectures). For simplicity, we resized the image to a square, where the resized image dimension equals to the power of 2. The exact size is the closest highest or equal power of 2 considering the minimum image size (independent of width and height) in the training dataset. For example the minimum image dimension (independent of width and height) for the dogs training dataset is 112, so the resized image size would be 128 which is 2^7.

    • Furthermore, selecting the resized image dimension as a power of 2 helps designing the layers of the CNN much easier (depends on strides and padding), because manually computing the size of intermediate CNN layers and output of the CNN layer becomes much straight forward.

    • Input tensor size (1, 3, 128, 128).

    • Batch size of 32: Initially 32 was choosen primarily because of memory constraints in my personal laptop. The input tensor size considering batches (32, 3, 128, 128)

    • No data augmentation: The first experiment is performed without augmentation, to check the capacity of the system under data constraint, and primarily done to quickly check the efficacy of the system.

    • We will experiment with 10 epochs. >> Design experiment 2, if required >> Run 10 epochs >> Repeat

    • Test dataset accuracy after epoch 10 is 1%. During training we saw the validation error gradually getting lower, however loosely speaking the rate is a very slow. It MAY BE associated with the training data size problem, meaning there is not enough example from which the system can learn, so that it can later generalize. Based on this assumption, we are designing experiment 2 which will artificially augment the data by randomly rotating the image within 10 degrees.

  • Experiment 2:

    • Simple Random Image Rotation within 10 degrees: Artificially augment the data by randomly rotating the image within 10 degrees.

    • We will experiment with 10 epochs. >> Design experiment 3, if required >> Run 10 epochs >> Repeat

    • Test dataset accuracy after epoch 10 is 1%. The results and the process for finding a learned model that is reliable is not good enough. Although like before, the validation error gradually getting lower, however the rate is still very slow, and did not much improve in comparison to experiment 1. So, solely augmenting the dataset is not helping.

    • Now designing experiment 3 by including batch normalization into CNN model architecture.

  • Experiment 3:

    • Added batch normalization to the CNN model architecture which was used on Experiment 1 and 2.

    • We will experiment with 10 epochs. >> Design experiment 4, if required >> Run 10 epochs >> Repeat

    • Test dataset accuracy after epoch 10 is 5%. This is amazing change. Eureka!

    • Now we plan to extend experiment 3 from the results of epoch 10 to epoch 30. Therefore, we will start off exactly from where we left experiment 3; so just run another 20 more epochs.

  • Experiment 4:
    • Added 20 more epochs to experiment 3.
    • Test dataset accuracy is now 11%. This is amazing change. Eureka! Exactly what the assignment required.
    • Based on the results, we want to see if adding more complex CNN layers (allowing more model flexibility) makes sense or not. The plan is to add other layer at the end of convolution, so the final depth changes to 128 from 64. Intuition says, it should: Lets actually see if this is the case or not.
    • Using 30 epochs, so that the results are at least somewhat comparable, in a loose sense.
  • Experiment 5:
    • Added other layer at the end of CNN model architecture, so at the output of the CNN the final depth changes to 128. This was done by extending experiment 4. The hypothesis: Designing complex CNN (allows the model to be flexible) should lead to a better model.
    • Test dataset accuracy is now 16%, with epoch = 30. This is amazing change. This seems a big change given the epochs were same (when comparing experiment 3+4 with experiment 5).
    • For the sake of the assignment, we would run a final experiment which is similar to experiment 5 however the epoch is 50.
  • Experiment 6 (Final Experiment):
    • Run experiment 5 again from scratch using epoch size of 50
    • Accuracy 23%.

(IMPLEMENTATION) Model Architecture

Create a CNN to classify dog breed. Use the template in the code cell below.

In [14]:
import torch.nn as nn
import torch.nn.functional as F

# define the CNN architecture
class Net(nn.Module):
    ### TODO: choose an architecture, and complete the class
    def __init__(self):
        super(Net, self).__init__()
        
        # Define layers of a CNN
        self.conv1 = nn.Conv2d( 3,  16, 3, stride = 1, padding = 1)
        self.conv2 = nn.Conv2d(16,  32, 3, stride = 1, padding = 1)
        self.conv3 = nn.Conv2d(32,  64, 3, stride = 1, padding = 1)
        self.conv4 = nn.Conv2d(64, 128, 3, stride = 1, padding = 1)
        
        # Fully Connected Layer
        self.fc1 = nn.Linear(128 * 8 * 8, 512)
        self.fc2 = nn.Linear(512, 256)
        self.fc3 = nn.Linear(256, 133)
        
        # Max pooling layer
        self.pool = nn.MaxPool2d(2, 2)
        self.dropout_fcl = nn.Dropout(0.5)
        
        # Batch Normalization Layers
        self.bn2D_1 = nn.BatchNorm2d( 16)
        self.bn2D_2 = nn.BatchNorm2d( 32)
        self.bn2D_3 = nn.BatchNorm2d( 64)
        self.bn2D_4 = nn.BatchNorm2d(128)
        
        
    def forward(self, x):
        # Define forward behavior using cNN, maxpooling, fcl and dropout
        
        # Convolutional and max pooling layers
        x = self.bn2D_1(self.pool(F.relu(self.conv1(x)))) # 128 x 128 ->   64 x 64
        x = self.bn2D_2(self.pool(F.relu(self.conv2(x)))) #  64 x  64 ->   32 x 32
        x = self.bn2D_3(self.pool(F.relu(self.conv3(x)))) #  32 x  32 ->   16 x 16
        x = self.bn2D_4(self.pool(F.relu(self.conv4(x)))) #  16 x  16 ->    8 x  8
        
        # Flatten the vector for fully connected layer
        x = x.view(-1, 128 * 8 * 8)
        x = self.dropout_fcl(x)
        
        # Fully connected layers
        x = self.dropout_fcl(F.relu(self.fc1(x)))
        x = self.dropout_fcl(F.relu(self.fc2(x)))
        x = self.fc3(x)
        return x

#-#-# You so NOT have to modify the code below this line. #-#-#

# instantiate the CNN
model_scratch = Net()

# move tensors to GPU if CUDA is available
if use_cuda: model_scratch.cuda()

Question 4: Outline the steps you took to get to your final CNN architecture and your reasoning at each step.

Answer:

Summary: After running 6 different structured experiments we have reached accuracy of 23% with the CNN model which has been designed from scratch. Based on the accuracy trends it can be hypothesized, given that we keep the CNN model constant (including the data processing steps) and increase the epoch from 50 to 100 it would lead to a better accuracy.

  • The lecturer advised to design the CNN architecture in a way which gradually reduces input image spatial resolution to a image resolution state which is much deeper compared to its length and width. Based on these notion, the CNN layer design was proposed: The input image size changed from 128 to 8, while the depth was increased from 3 to 128.
  • The CNN hyperparameter controlling the depth was increased as a multiple of 2. This was choosen so that we can quickly, but gradually, increase the depth 42 times its original (3 x 42 ~ 128) in a matter of few layers.
  • Dropout was introduced to avoid overfitting.
  • We needed a system which can generalize well when subjected to shifting input distribution, a phenomenon known as the covaraite shift [Reference: https://www.youtube.com/watch?v=nUUqwaxLnWs]. According to Dr. Andrew Ng: Shift in input distribution disrupts the learning capacity of the system. However this can be minimized using batch normalization. Added benifit of batch normalization is that it also works as a passive regularizer. Therefore added batch normalizers.

The exact reason why we choose this particular CNN model architecture is outlined in the following as experiments, how learning from one experiment lead to the next. For detailed structured reasoning please study our experiments process.

  • Experiment 1:

    • The lecturer advised to design the CNN architecture in a way which gradually reduces input image spatial resolution to a image resolution state which is much deeper compared to its length and width. Based on these notion, the CNN layer design was proposed: The input image size changed from 128 to 16, while the depth was increased from 3 to 64.
    • The CNN hyperparameter controlling the depth was increased as a multiple of 2. This was choosen so that we can quickly, but gradually, increase the depth 20 times its original (3 x 20 ~ 64) in a matter of few layers.

    • The fully connected layers was design in a way so that it can also reach the output requirment in 3 gradual steps.

    • Why choose 3? In all honestly, it is just a random initial experiment to get started and iterate based on subsequent finding. Note: As an individual I have a bias: I do not like abrupt changes, therefore the architecture also reflects some of my though process, which most likely has no mathematical basis (therefore, I called it random).

    • Dropout was introduced to avoid overfitting.

    • Test dataset accuracy after epoch 10 is 1%. During training we saw the validation error gradually getting lower, however loosely speaking the rate is a very slow. It MAY BE associated with the training data size problem, meaning there is not enough example from which the system can learn, so that it can later generalize. Based on this assumption, we are designing experiment 2 which will artificially augment the data by randomly rotating the image within 10 degrees.

  • Experiment 2:

    • No change in the CNN architecture, exactly the same as experiment 1.
    • Test dataset accuracy after epoch 10 is 1%. The results and the process for finding a learned model that is reliable is not good enough. Although like before, the validation error gradually getting lower, however the rate is still very slow, and did not much improve in comparison to experiment 1. So, solely augmenting the dataset is not helping.

    • We needed a system which can generalize well when subjected to shifting input distribution, a phenomenon known as the covaraite shift [Reference: https://www.youtube.com/watch?v=nUUqwaxLnWs]. According to Dr. Andrew Ng: Shift in input distribution disrupts the learning capacity of the system. However this can me minimized using batch normalization. Therefore, experiment 3 changes the CNN architecture to take into consideration batch normalization.

    • Added benifit of batch normalization is that it also works as a passive regularizer.

  • Experiment 3:
    • Added batch normalization to the CNN which was used on Experiment 1 and 2.
    • Test dataset accuracy after epoch 10 is 5%. This is amazing change. Eureka!
    • Now we plan to extend experiment 3 from the result of epoch 10 to epoch 30. We will start off exactly from where we left experiment 3. So run another 20 epochs more.
  • Experiment 4:
    • Added 20 more epochs to experiment 3.
    • Test dataset accuracy is now 11%. This is amazing change. Eureka! Exactly what the assignment required.
    • Based on the results, we want to see if adding more complex CNN layers (allowing more model flexibility) makes sense or not. The plan is to add other layer at the end of convolution, so the final depth changes to 128 from 64. Intuition says, it should: Lets actually see if this is the case or not.
    • Using 30 epochs, so that the results are at least somewhat comparable, in a loose sense.
  • Experiment 5:
    • Added other layer at the end of CNN model architecture, so at the output of the CNN the final depth changes to 128. This was done by extending experiment 4. The hypothesis: Designing complex CNN (allows the model to be flexible) should lead to a better model.
    • Test dataset accuracy is now 16%, with epoch = 30. This is amazing change. This seems a big change given the epochs were same (when comparing experiment 3+4 with experiment 5).
    • For the sake of the assignment, we would run a final experiment which is similar to experiment 5 however the epoch is 50.
  • Experiment 6 (Final Experiment):
    • Run experiment 5 again from scratch using epoch size of 50
    • Accuracy 23%.

(IMPLEMENTATION) Specify Loss Function and Optimizer

Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_scratch, and the optimizer as optimizer_scratch below.

In [15]:
import torch.optim as optim

### TODO: select loss function (categorical cross-entropy)
criterion_scratch = nn.CrossEntropyLoss()

### TODO: select optimizer
optimizer_scratch = optim.SGD(model_scratch.parameters(), lr = 0.01)

(IMPLEMENTATION) Train and Validate the Model

Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_scratch.pt'.

In [16]:
def train(n_epochs, loaders, model, optimizer, criterion, use_cuda, save_path):
    """returns trained model"""
    # initialize tracker for minimum validation loss
    valid_loss_min = np.Inf 
    
    for epoch in range(1, n_epochs+1):
        # initialize variables to monitor training and validation loss
        train_loss = 0.0
        valid_loss = 0.0
        
        ###################
        # train the model #
        ###################
        model.train()
        for batch_idx, (data, target) in enumerate(loaders['train']):
            # move to GPU
            if use_cuda: data, target = data.cuda(), target.cuda()
            
            # clear the gradients of all optimized variables
            optimizer.zero_grad()
            
            # forward pass: compute predicted outputs by passing inputs to the model
            output = model(data)
            
            # calculate the batch loss
            loss = criterion(output, target)
            
            # backward pass: compute gradient of the loss with respect to model parameters
            loss.backward()
            
            # perform a single optimization step (parameter update)
            optimizer.step()
        
            # update training loss
            train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data - train_loss))

        ######################    
        # validate the model #
        ######################
        model.eval()
        for batch_idx, (data, target) in enumerate(loaders['valid']):
            # move to GPU
            if use_cuda: data, target = data.cuda(), target.cuda()
            
            # forward pass: compute predicted outputs by passing inputs to the model
            output = model(data)
            
            # calculate the batch loss
            loss = criterion(output, target)
            
            # update average validation loss 
            valid_loss = valid_loss + ((1 / (batch_idx + 1)) * (loss.data - valid_loss))
        
        # calculate average losses
        train_loss = train_loss/len(loaders['train'].dataset)
        valid_loss = valid_loss/len(loaders['valid'].dataset)
            
        # print training/validation statistics 
        print('Epoch: {} \tTraining Loss: {:.6f} \tValidation Loss: {:.6f}'.format(epoch, train_loss, valid_loss))
        
        ## TODO: save the model if validation loss has decreased
        # save model if validation loss has decreased
        if valid_loss <= valid_loss_min:
            print('Validation loss decreased from {:.6f} to --> {:.6f}).  Saving model ...\n'.format(
            valid_loss_min,
            valid_loss))
            torch.save(model.state_dict(), save_path)
            valid_loss_min = valid_loss
            
    # return trained model
    return model
In [17]:
epochs = 50

try: 
    # load the model that got the best validation accuracy
    model_scratch.load_state_dict(torch.load('model_scratch.pt'))
    print('model_scratch.pt found! Start training using the best saved model\'s weights as initial weights')
except: print('model_scratch.pt not found! Did not find an already pre-saved model so training purely from scratch')

# Train the model
model_scratch = train(epochs, loaders_scratch, model_scratch, optimizer_scratch, 
                      criterion_scratch, use_cuda, 'model_scratch.pt')
model_scratch.pt not found! Did not find an already pre-saved model so training purely from scratch
Epoch: 1 	Training Loss: 0.000733 	Validation Loss: 0.005837
Validation loss decreased from inf to --> 0.005837).  Saving model ...

Epoch: 2 	Training Loss: 0.000728 	Validation Loss: 0.005798
Validation loss decreased from 0.005837 to --> 0.005798).  Saving model ...

Epoch: 3 	Training Loss: 0.000721 	Validation Loss: 0.005712
Validation loss decreased from 0.005798 to --> 0.005712).  Saving model ...

Epoch: 4 	Training Loss: 0.000707 	Validation Loss: 0.005557
Validation loss decreased from 0.005712 to --> 0.005557).  Saving model ...

Epoch: 5 	Training Loss: 0.000687 	Validation Loss: 0.005370
Validation loss decreased from 0.005557 to --> 0.005370).  Saving model ...

Epoch: 6 	Training Loss: 0.000670 	Validation Loss: 0.005261
Validation loss decreased from 0.005370 to --> 0.005261).  Saving model ...

Epoch: 7 	Training Loss: 0.000655 	Validation Loss: 0.005047
Validation loss decreased from 0.005261 to --> 0.005047).  Saving model ...

Epoch: 8 	Training Loss: 0.000644 	Validation Loss: 0.005006
Validation loss decreased from 0.005047 to --> 0.005006).  Saving model ...

Epoch: 9 	Training Loss: 0.000632 	Validation Loss: 0.004962
Validation loss decreased from 0.005006 to --> 0.004962).  Saving model ...

Epoch: 10 	Training Loss: 0.000620 	Validation Loss: 0.004946
Validation loss decreased from 0.004962 to --> 0.004946).  Saving model ...

Epoch: 11 	Training Loss: 0.000613 	Validation Loss: 0.004786
Validation loss decreased from 0.004946 to --> 0.004786).  Saving model ...

Epoch: 12 	Training Loss: 0.000602 	Validation Loss: 0.004786
Validation loss decreased from 0.004786 to --> 0.004786).  Saving model ...

Epoch: 13 	Training Loss: 0.000595 	Validation Loss: 0.004701
Validation loss decreased from 0.004786 to --> 0.004701).  Saving model ...

Epoch: 14 	Training Loss: 0.000586 	Validation Loss: 0.004730
Epoch: 15 	Training Loss: 0.000578 	Validation Loss: 0.004638
Validation loss decreased from 0.004701 to --> 0.004638).  Saving model ...

Epoch: 16 	Training Loss: 0.000570 	Validation Loss: 0.004549
Validation loss decreased from 0.004638 to --> 0.004549).  Saving model ...

Epoch: 17 	Training Loss: 0.000562 	Validation Loss: 0.004508
Validation loss decreased from 0.004549 to --> 0.004508).  Saving model ...

Epoch: 18 	Training Loss: 0.000553 	Validation Loss: 0.004511
Epoch: 19 	Training Loss: 0.000548 	Validation Loss: 0.004536
Epoch: 20 	Training Loss: 0.000541 	Validation Loss: 0.004437
Validation loss decreased from 0.004508 to --> 0.004437).  Saving model ...

Epoch: 21 	Training Loss: 0.000534 	Validation Loss: 0.004413
Validation loss decreased from 0.004437 to --> 0.004413).  Saving model ...

Epoch: 22 	Training Loss: 0.000526 	Validation Loss: 0.004369
Validation loss decreased from 0.004413 to --> 0.004369).  Saving model ...

Epoch: 23 	Training Loss: 0.000520 	Validation Loss: 0.004355
Validation loss decreased from 0.004369 to --> 0.004355).  Saving model ...

Epoch: 24 	Training Loss: 0.000513 	Validation Loss: 0.004281
Validation loss decreased from 0.004355 to --> 0.004281).  Saving model ...

Epoch: 25 	Training Loss: 0.000505 	Validation Loss: 0.004270
Validation loss decreased from 0.004281 to --> 0.004270).  Saving model ...

Epoch: 26 	Training Loss: 0.000501 	Validation Loss: 0.004147
Validation loss decreased from 0.004270 to --> 0.004147).  Saving model ...

Epoch: 27 	Training Loss: 0.000493 	Validation Loss: 0.004227
Epoch: 28 	Training Loss: 0.000487 	Validation Loss: 0.004245
Epoch: 29 	Training Loss: 0.000481 	Validation Loss: 0.004181
Epoch: 30 	Training Loss: 0.000475 	Validation Loss: 0.004215
Epoch: 31 	Training Loss: 0.000466 	Validation Loss: 0.004151
Epoch: 32 	Training Loss: 0.000460 	Validation Loss: 0.004166
Epoch: 33 	Training Loss: 0.000459 	Validation Loss: 0.004106
Validation loss decreased from 0.004147 to --> 0.004106).  Saving model ...

Epoch: 34 	Training Loss: 0.000449 	Validation Loss: 0.004058
Validation loss decreased from 0.004106 to --> 0.004058).  Saving model ...

Epoch: 35 	Training Loss: 0.000441 	Validation Loss: 0.004173
Epoch: 36 	Training Loss: 0.000436 	Validation Loss: 0.004062
Epoch: 37 	Training Loss: 0.000432 	Validation Loss: 0.003981
Validation loss decreased from 0.004058 to --> 0.003981).  Saving model ...

Epoch: 38 	Training Loss: 0.000424 	Validation Loss: 0.003996
Epoch: 39 	Training Loss: 0.000418 	Validation Loss: 0.003882
Validation loss decreased from 0.003981 to --> 0.003882).  Saving model ...

Epoch: 40 	Training Loss: 0.000410 	Validation Loss: 0.003926
Epoch: 41 	Training Loss: 0.000410 	Validation Loss: 0.003901
Epoch: 42 	Training Loss: 0.000402 	Validation Loss: 0.003868
Validation loss decreased from 0.003882 to --> 0.003868).  Saving model ...

Epoch: 43 	Training Loss: 0.000392 	Validation Loss: 0.003827
Validation loss decreased from 0.003868 to --> 0.003827).  Saving model ...

Epoch: 44 	Training Loss: 0.000390 	Validation Loss: 0.003856
Epoch: 45 	Training Loss: 0.000385 	Validation Loss: 0.003999
Epoch: 46 	Training Loss: 0.000374 	Validation Loss: 0.003843
Epoch: 47 	Training Loss: 0.000370 	Validation Loss: 0.003816
Validation loss decreased from 0.003827 to --> 0.003816).  Saving model ...

Epoch: 48 	Training Loss: 0.000362 	Validation Loss: 0.003851
Epoch: 49 	Training Loss: 0.000362 	Validation Loss: 0.003821
Epoch: 50 	Training Loss: 0.000351 	Validation Loss: 0.003930

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 10%.

In [18]:
def test(loaders, model, criterion, use_cuda):

    # monitor test loss and accuracy
    test_loss = 0.
    correct = 0.
    total = 0.

    model.eval()
    for batch_idx, (data, target) in enumerate(loaders['test']):
        # move to GPU
        if use_cuda: data, target = data.cuda(), target.cuda()
        
        # forward pass: compute predicted outputs by passing inputs to the model
        output = model(data)
        
        # calculate the loss
        loss = criterion(output, target)
        
        # update average test loss 
        test_loss = test_loss + ((1 / (batch_idx + 1)) * (loss.data - test_loss))
        
        # convert output probabilities to predicted class
        pred = output.data.max(1, keepdim=True)[1]
        
        # compare predictions to true label
        correct += np.sum(np.squeeze(pred.eq(target.data.view_as(pred))).cpu().numpy())
        
        total += data.size(0)
            
    print('Test Loss: {:.6f}\n'.format(test_loss))

    print('\nTest Accuracy: %2d%% (%2d/%2d)' % (100. * correct / total, correct, total))
In [19]:
try: 
    # load the model that got the best validation accuracy, and call the test function
    model_scratch.load_state_dict(torch.load('model_scratch.pt'))
    test(loaders_scratch, model_scratch, criterion_scratch, use_cuda)
except: print('model_scratch.pt not found! Could not load the model that got the best validation accuracy')
Test Loss: 3.177875


Test Accuracy: 23% (197/836)

Step 4: Create a CNN to Classify Dog Breeds (using Transfer Learning)

You will now use transfer learning to create a CNN that can identify dog breed from images. Your CNN must attain at least 60% accuracy on the test set.

(IMPLEMENTATION) Specify Data Loaders for the Dog Dataset

Use the code cell below to write three separate data loaders for the training, validation, and test datasets of dog images (located at dogImages/train, dogImages/valid, and dogImages/test, respectively).

If you like, you are welcome to use the same data loaders from the previous step, when you created a CNN from scratch.

In [20]:
## TODO: Specify data loaders
data_transform_trainVGG = transforms.Compose([transforms.Resize(size = (224, 224)), transforms.RandomRotation(10),
                                              transforms.ToTensor(), transforms.Normalize(mean = [0.485, 0.456, 0.406], 
                                                                                          std = [0.229, 0.224, 0.225])])

data_transform_othersVGG = transforms.Compose([transforms.Resize(size = (224, 224)), transforms.ToTensor(),  
                                               transforms.Normalize(mean = [0.485, 0.456, 0.406], 
                                                                    std = [0.229, 0.224, 0.225])])

## TODO: Specify data loaders
# load and transform data using ImageFolder
train_data = datasets.ImageFolder(train_dir, transform = data_transform_trainVGG)
valid_data = datasets.ImageFolder(valid_dir, transform = data_transform_othersVGG)
test_data = datasets.ImageFolder(test_dir, transform = data_transform_othersVGG)

# print out some data stats
print('Num training images: ', len(train_data))
print('Num valid images: ', len(valid_data))
print('Num test images: ', len(test_data))

# define dataloader parameters
batch_size = 32

# prepare data loaders
train_loader = torch.utils.data.DataLoader(train_data, batch_size = batch_size, shuffle = True)
valid_loader = torch.utils.data.DataLoader(valid_data, batch_size = batch_size, shuffle = True)
test_loader = torch.utils.data.DataLoader(test_data, batch_size = batch_size, shuffle = True) 

loaders_transfer = {'train': train_loader, 'valid' : valid_loader, 'test' : test_loader}
Num training images:  6680
Num valid images:  835
Num test images:  836

(IMPLEMENTATION) Model Architecture

Use transfer learning to create a CNN to classify dog breed. Use the code cell below, and save your initialized model as the variable model_transfer.

In [21]:
import torchvision.models as models
import torch.nn as nn

## TODO: Specify model architecture 
model_transfer = models.vgg16(pretrained = True)

# Move model to GPU if CUDA is available
use_cuda = torch.cuda.is_available()
if use_cuda: model_transfer = model_transfer.cuda()
    
# Freeze training for all "features" layers
for param in model_transfer.features.parameters(): param.requires_grad = False   
model_transfer.classifier[6].out_features = 133

print(model_transfer)
VGG(
  (features): Sequential(
    (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (1): ReLU(inplace)
    (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (3): ReLU(inplace)
    (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (6): ReLU(inplace)
    (7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (8): ReLU(inplace)
    (9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (11): ReLU(inplace)
    (12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (13): ReLU(inplace)
    (14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (15): ReLU(inplace)
    (16): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (17): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (18): ReLU(inplace)
    (19): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (20): ReLU(inplace)
    (21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (22): ReLU(inplace)
    (23): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
    (24): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (25): ReLU(inplace)
    (26): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (27): ReLU(inplace)
    (28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
    (29): ReLU(inplace)
    (30): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  )
  (classifier): Sequential(
    (0): Linear(in_features=25088, out_features=4096, bias=True)
    (1): ReLU(inplace)
    (2): Dropout(p=0.5)
    (3): Linear(in_features=4096, out_features=4096, bias=True)
    (4): ReLU(inplace)
    (5): Dropout(p=0.5)
    (6): Linear(in_features=4096, out_features=133, bias=True)
  )
)

Question 5: Outline the steps you took to get to your final CNN architecture and your reasoning at each step. Describe why you think the architecture is suitable for the current problem.

Answer:

  • Experiment 1:
    • We did not change much in the VGG16 CNN model architecture; just replaced the final output layer to 133 because we are using 133 dog breed as output, where as the original VGG16 is designed for different number of classes. This was chosen because the new data set is small, new data is similar to original training data.
    • Accuracy achieved 84%.
  • Experiment 2:
    • Run experiment 1 using 20 epochs
    • Accuracy achieved 84%.

(IMPLEMENTATION) Specify Loss Function and Optimizer

Use the next code cell to specify a loss function and optimizer. Save the chosen loss function as criterion_transfer, and the optimizer as optimizer_transfer below.

In [22]:
criterion_transfer = nn.CrossEntropyLoss()
optimizer_transfer = optim.SGD(model_transfer.classifier.parameters(), lr = 0.01)

(IMPLEMENTATION) Train and Validate the Model

Train and validate your model in the code cell below. Save the final model parameters at filepath 'model_transfer.pt'.

In [23]:
# train the model
epochs = 20

try: 
    # load the model that got the best validation accuracy
    model_transfer.load_state_dict(torch.load('model_transfer.pt'))
    print('model_transfer.pt found! Start training using the best saved tranfer model\'s weights as initial weights')
except: print('model_transfer.pt not found! Did not find an already pre-saved tranfer model so training purely from scratch')

model_transfer = train(epochs, loaders_transfer, model_transfer, optimizer_transfer, 
                       criterion_transfer, use_cuda, 'model_transfer.pt')
model_transfer.pt not found! Did not find an already pre-saved tranfer model so training purely from scratch
Epoch: 1 	Training Loss: 0.000607 	Validation Loss: 0.001593
Validation loss decreased from inf to --> 0.001593).  Saving model ...

Epoch: 2 	Training Loss: 0.000206 	Validation Loss: 0.000928
Validation loss decreased from 0.001593 to --> 0.000928).  Saving model ...

Epoch: 3 	Training Loss: 0.000139 	Validation Loss: 0.000742
Validation loss decreased from 0.000928 to --> 0.000742).  Saving model ...

Epoch: 4 	Training Loss: 0.000111 	Validation Loss: 0.000714
Validation loss decreased from 0.000742 to --> 0.000714).  Saving model ...

Epoch: 5 	Training Loss: 0.000088 	Validation Loss: 0.000639
Validation loss decreased from 0.000714 to --> 0.000639).  Saving model ...

Epoch: 6 	Training Loss: 0.000071 	Validation Loss: 0.000609
Validation loss decreased from 0.000639 to --> 0.000609).  Saving model ...

Epoch: 7 	Training Loss: 0.000063 	Validation Loss: 0.000589
Validation loss decreased from 0.000609 to --> 0.000589).  Saving model ...

Epoch: 8 	Training Loss: 0.000054 	Validation Loss: 0.000572
Validation loss decreased from 0.000589 to --> 0.000572).  Saving model ...

Epoch: 9 	Training Loss: 0.000047 	Validation Loss: 0.000539
Validation loss decreased from 0.000572 to --> 0.000539).  Saving model ...

Epoch: 10 	Training Loss: 0.000041 	Validation Loss: 0.000522
Validation loss decreased from 0.000539 to --> 0.000522).  Saving model ...

Epoch: 11 	Training Loss: 0.000036 	Validation Loss: 0.000550
Epoch: 12 	Training Loss: 0.000032 	Validation Loss: 0.000597
Epoch: 13 	Training Loss: 0.000028 	Validation Loss: 0.000537
Epoch: 14 	Training Loss: 0.000025 	Validation Loss: 0.000652
Epoch: 15 	Training Loss: 0.000022 	Validation Loss: 0.000568
Epoch: 16 	Training Loss: 0.000020 	Validation Loss: 0.000544
Epoch: 17 	Training Loss: 0.000018 	Validation Loss: 0.000583
Epoch: 18 	Training Loss: 0.000017 	Validation Loss: 0.000574
Epoch: 19 	Training Loss: 0.000016 	Validation Loss: 0.000619
Epoch: 20 	Training Loss: 0.000014 	Validation Loss: 0.000585

(IMPLEMENTATION) Test the Model

Try out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy. Ensure that your test accuracy is greater than 60%.

In [24]:
try: 
    # load the model that got the best validation accuracy, and call the test function
    model_transfer.load_state_dict(torch.load('model_transfer.pt'))
    test(loaders_transfer, model_transfer, criterion_transfer, use_cuda)
except: print('model_transfer.pt not found! Could not load the model that got the best validation accuracy')
Test Loss: 0.546302


Test Accuracy: 84% (704/836)

(IMPLEMENTATION) Predict Dog Breed with the Model

Write a function that takes an image path as input and returns the dog breed (Affenpinscher, Afghan hound, etc) that is predicted by your model.

In [25]:
### TODO: Write a function that takes a path to an image as input
### and returns the dog breed that is predicted by the model.

# list of class names by index, i.e. a name can be accessed like class_names[0]
class_names = [item[4:].replace("_", " ") for item in train_data.classes]

def predict_breed_transfer(img_path):
    '''
    Predicts dog breed using model developed using tranfer learning.
    # The idea is just load the image and it returns the predicted breed
    
    Args:
        img_path: path to an image
        
    Returns:
        returns the name of the breed
    '''
    
    ## TODO: Complete the function.
    ## Load and pre-process an image from the given img_path
    ## Return the *index* of the predicted class for that image
    img = Image.open(img_path)
    
    data_transform = transforms.Compose([transforms.Resize(size=(224, 224)),
                                         transforms.ToTensor(),
                                         transforms.Normalize(
                                             mean = [0.485, 0.456, 0.406], 
                                             std  = [0.229, 0.224, 0.225])])
    
    model_transfer.eval()
    
    # Transform: Properly reshape, convert to tensor, and normalize according to VGG16 rules
    input_img_tensor = data_transform(img).reshape(1, 3, 224, 224)
                             
    # move tensors to GPU if CUDA is available
    use_cuda = torch.cuda.is_available()
    if use_cuda: input_img_tensor = input_img_tensor.cuda() 
                          
    # forward pass: compute predicted outputs by passing inputs to the model
    output = model_transfer(input_img_tensor)
    
    # convert output probabilities to predicted class
    # predicted class index
    _, pred_class_idx = torch.max(output, 1)
    
    return class_names[pred_class_idx]

output = predict_breed_transfer('./dogImages/test/034.Boxer/Boxer_02397.jpg')
print(output)
Boxer

Step 5: Write your Algorithm

Write an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither. Then,

  • if a dog is detected in the image, return the predicted breed.
  • if a human is detected in the image, return the resembling dog breed.
  • if neither is detected in the image, provide output that indicates an error.

You are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the face_detector and human_detector functions developed above. You are required to use your CNN from Step 4 to predict dog breed.

Some sample output for our algorithm is provided below, but feel free to design your own user experience!

Sample Human Output

(IMPLEMENTATION) Write your Algorithm

In [26]:
### TODO: Write your algorithm.
### Feel free to use as many code cells as needed.

def run_app(img_path):
    ## handle cases for a human face, dog, and neither
    breed = False
    is_dog = dog_detector(img_path)
    is_human = face_detector(img_path)
    
    try:
        breed = predict_breed_transfer(img_path)
        
        if is_dog or breed:
            print('Hello', breed+'!')
            plt.imshow(cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB))
            plt.show(); print('')
            return breed
        
        elif is_human:
            print('Hello human!', 'Although human, you look more like ...', breed + '!')
            plt.imshow(cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB))
            plt.show(); print('')
            return breed
        else: 
            print('Input error: Neither a dog or a human\n')
            return None
        
    except: print('Input error: Neither a dog or a human\n')

run_app('./images/Curly-coated_retriever_03896.jpg')
Hello Curly-coated retriever!

Out[26]:
'Curly-coated retriever'
In [27]:
run_app('./personal_images/ehsan.jpg')
Hello Chinese crested!

Out[27]:
'Chinese crested'
In [28]:
run_app('./personal_images/ehsan2.jpg')
Hello Dachshund!

Out[28]:
'Dachshund'
In [29]:
run_app('./personal_images/tazy1.jpg')
Input error: Neither a dog or a human

In [30]:
run_app('./personal_images/tazy2.jpg')
Hello Dalmatian!

Out[30]:
'Dalmatian'
In [31]:
run_app('./personal_images/tazy3.jpg')
Input error: Neither a dog or a human

In [32]:
run_app('./personal_images/cat2.jpg')
Hello Japanese chin!

Out[32]:
'Japanese chin'

Step 6: Test Your Algorithm

In this section, you will take your new algorithm for a spin! What kind of dog does the algorithm think that you look like? If you have a dog, does it predict your dog's breed accurately? If you have a cat, does it mistakenly think that your cat is a dog?

(IMPLEMENTATION) Test Your Algorithm on Sample Images!

Test your algorithm at least six images on your computer. Feel free to use any images you like. Use at least two human and two dog images.

Question 6: Is the output better than you expected :) ? Or worse :( ? Provide at least three possible points of improvement for your algorithm.

Answer: (Three possible points for improvement)

  • This is an interesting application - pure entertainment. To be honest, I was not really expecting anything however, when ehsan2.jpg got the Dachshund as breed it was interesting. I could see how the black-woolen jacket and brown face can be related to Dachshund.

    • The human face detector needs to be improved; it is not able to detect human faces with consistency.
    • Experiment with different pretrained network like Inception-v3, ResNet-50 to improve the dog breed detection scheme.
    • Given a human face, in addition to outputing the resembling dog breed, also output a transformed image stitching the resembling dog's nose and ears to the human face.
In [33]:
## TODO: Execute your algorithm from Step 6 on
## at least 6 images on your computer.
## Feel free to use as many code cells as needed.

## suggested code, below
filelist = np.array(glob("./personal_images/*"))
for file in filelist:
    print('Running the app on filename: ', file)
    run_app(file)
Running the app on filename:  ./personal_images/shiba.jpg
Hello Akita!
Running the app on filename:  ./personal_images/ayaat2.jpg
Input error: Neither a dog or a human

Running the app on filename:  ./personal_images/tazy2.jpg
Hello Dalmatian!
Running the app on filename:  ./personal_images/zarib2.jpg
Input error: Neither a dog or a human

Running the app on filename:  ./personal_images/lilac.jpg
Hello American eskimo dog!
Running the app on filename:  ./personal_images/joey.jpg
Hello Brussels griffon!
Running the app on filename:  ./personal_images/tazy6.jpg
Hello Curly-coated retriever!
Running the app on filename:  ./personal_images/Labrador_retriever_06457.jpg
Hello Labrador retriever!
Running the app on filename:  ./personal_images/zarib.jpg
Input error: Neither a dog or a human

Running the app on filename:  ./personal_images/Brittany_02625.jpg
Hello Brittany!
Running the app on filename:  ./personal_images/American_water_spaniel_00648.jpg
Hello American water spaniel!
Running the app on filename:  ./personal_images/tazy5.jpg
Hello Cane corso!
Running the app on filename:  ./personal_images/tazy3.jpg
Input error: Neither a dog or a human

Running the app on filename:  ./personal_images/Curly-coated_retriever_03896.jpg
Hello Curly-coated retriever!
Running the app on filename:  ./personal_images/Labrador_retriever_06455.jpg
Hello Chesapeake bay retriever!
Running the app on filename:  ./personal_images/cat.jpg
Hello Japanese chin!
Running the app on filename:  ./personal_images/tazy1.jpg
Input error: Neither a dog or a human

Running the app on filename:  ./personal_images/ayaat.jpg
Input error: Neither a dog or a human

Running the app on filename:  ./personal_images/Labrador_retriever_06449.jpg
Hello Labrador retriever!
Running the app on filename:  ./personal_images/ehsan.jpg
Hello Chinese crested!
Running the app on filename:  ./personal_images/bengal_cat.jpg
Hello French bulldog!
Running the app on filename:  ./personal_images/tazy4.jpg
Input error: Neither a dog or a human

Running the app on filename:  ./personal_images/bengal_cat2.jpg
Hello Pembroke welsh corgi!
Running the app on filename:  ./personal_images/nana.jpg
Hello American foxhound!
Running the app on filename:  ./personal_images/Welsh_springer_spaniel_08203.jpg
Hello Welsh springer spaniel!
Running the app on filename:  ./personal_images/cat2.jpg
Hello Japanese chin!
Running the app on filename:  ./personal_images/ehsan2.jpg
Hello Dachshund!